<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>29.处理购物车中的重复商品</title>
</head>

<body>
  <script>
    let cart = [
      { name: "iphone", price: 12000 },
      { name: "imac", price: 25000 },
      { name: "ipad", price: 3600 }
    ];

    // 获取超过指定价格的商品名
    // reduce 第二个参数可以是数组
    function getNameByPrice (goods, price) {
      return goods.reduce(function (arr, cur) {
        if (cur.price > price) arr.push(cur);
        return arr;
      }, []).map((item) => item.name);
    }
    console.log(getNameByPrice(cart, 10000));
    //去除重复元素
    let hd = [1, 2, 3, 3, 1, 4, 2];
    let newArr = hd.reduce(function (arr, cur) {
      if (arr.includes(cur) === false) {
        arr.push(cur);
      }
      return arr;
    }, []);
    console.log(newArr);
    // 去掉引用类型重复的商品
    let cart2 = [
      { name: "iphone", price: 12000 },
      { name: "iphone", price: 12000 },
      { name: "imac", price: 25000 },
      { name: "imac", price: 25000 },
      { name: "ipad", price: 3600 },
      { name: "ipad", price: 3600 }
    ];

    let newCart2 = cart2.reduce(function(arr,cur){
      let find = arr.find(function(item){
        return item.name === cur.name;
      })
      if(!find) arr.push(cur);
      return arr;
    },[]);
    console.log(cart2);
    console.log(newCart2);
  </script>
</body>

</html>